package com.java.exer1;

import org.junit.Test;

import java.util.Arrays;

/**
 * 将一个字符串反转，将字符串中指定位置部分进行反转 。比如“abcdefg”反转为“abfedcg”
 *
 * @author shkstart
 * @create 2021-01-05 22:00
 */
public class StringTest_3 {
    public static void main(String[] args) {
        //自己写的
        String s1 = "abcdefg";
        int index = 2;
        char[] a = s1.toCharArray();
        for (int i = 0; i < 2; i++) {
            char t = a[index];
            a[index] = a[a.length - 2 - i];
            a[a.length - 2 - i] = t;
            index++;
        }
        System.out.println(Arrays.toString(a));
    }

    //讲的 方式一：
    @Test
    public void test1() {
        String s1 = "abcdefg";
        String a = reserve1(s1, 2, 5);
        System.out.println(a);

    }

    public String reserve1(String s1, int startIndex, int endIndex) {
        char[] a = s1.toCharArray();
        for (int i = startIndex, j = endIndex; i < j; i++, j--) {
            char t = a[i];
            a[i] = a[j];
            a[j] = t;
        }
        return new String(a);
    }

    //方式二：使用String字符串拼接
    @Test
    public void test2() {
        String s1 = "abcdefg";
        reserve2(s1, 2, 5);
    }

    public void reserve2(String str, int starIndex, int endIndex) {
        String first = str.substring(0, starIndex);
//        String middel=str.substring(starIndex,endIndex);

        for (int i = endIndex; i > starIndex - 1; i--) {
            first += str.charAt(i);
        }
//        for (int i = endIndex; i <str.length() ; i++) {
//            first+=str.charAt(i);
//        }
        first += str.substring(endIndex + 1);
        System.out.println(first);
    }

    //方式三：放进StringBuffer中
    @Test
    public void test3() {
        String s1 = new String("abcdefghi");
        reserve3(s1, 2, 6);
    }

    public void reserve3(String str, int starIndex, int endIndex) {
        StringBuffer s1 = new StringBuffer(str.length());
        s1.append(str.substring(0, starIndex));
        for (int i = endIndex; i > starIndex - 1; i--) {
            s1.append(str.charAt(i));
        }
        s1.append(str.substring(endIndex + 1));
        System.out.println(s1);
    }

}
